import React, { useState, useEffect, useCallback } from 'react';
import { Button, Modal, Alert, Steps, Typography } from 'antd';
import { AudioOutlined, CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';

const { Step } = Steps;
const { Title, Text } = Typography;

export default function MicrophonePermission({ children }) {
  const [permissionStatus, setPermissionStatus] = useState('unknown'); // unknown, granted, denied, prompt
  const [showHelp, setShowHelp] = useState(false);
  const [isHttps, setIsHttps] = useState(false);
  const [isChecking, setIsChecking] = useState(false); // 防止重复检查
  const [hasError, setHasError] = useState(false); // 错误状态
  const [initialized, setInitialized] = useState(false); // 跟踪是否已初始化

  const checkMicrophonePermission = useCallback(async () => {
    try {
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        setPermissionStatus('not-supported');
        return;
      }

      // 尝试查询权限状态
      if (navigator.permissions) {
        try {
          const permission = await navigator.permissions.query({ name: 'microphone' });
          const currentState = permission.state;
          setPermissionStatus(currentState);
          
          // 监听权限状态变化（只设置一次）
          if (!permission.onchange) {
            permission.onchange = () => {
              const newState = permission.state;
              setPermissionStatus(prevState => {
                if (prevState !== newState) {
                  console.log('权限状态变化:', prevState, '->', newState);
                  return newState;
                }
                return prevState;
              });
            };
          }
        } catch (e) {
          console.log('无法查询权限状态:', e);
          setPermissionStatus('prompt');
        }
      } else {
        setPermissionStatus('prompt');
      }
    } catch (error) {
      console.error('检查麦克风权限时出错:', error);
      setPermissionStatus('prompt');
    }
  }, []); // 不依赖任何状态


  useEffect(() => {
    // 只在组件初次挂载时执行一次
    if (initialized || isChecking || hasError) {
      return;
    }

    try {
      // 检查是否使用HTTPS或localhost
      const isSecure = window.location.protocol === 'https:' || 
                      window.location.hostname === 'localhost' || 
                      window.location.hostname === '127.0.0.1';
      setIsHttps(isSecure);

      // 标记为已初始化
      setInitialized(true);
      setIsChecking(true);
      
      checkMicrophonePermission().finally(() => {
        setIsChecking(false);
      });
    } catch (error) {
      console.error('初始化麦克风权限组件时出错:', error);
      setHasError(true);
      setIsChecking(false);
      setInitialized(true);
    }
  }, [initialized, isChecking, hasError, checkMicrophonePermission]);

  const requestPermission = async () => {
    if (isChecking) return; // 防止重复请求
    
    setIsChecking(true);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      // 如果成功，立即停止流
      stream.getTracks().forEach(track => track.stop());
      setPermissionStatus('granted');
      setShowHelp(false);
      setHasError(false);
    } catch (error) {
      console.error('请求麦克风权限失败:', error);
      if (error.name === 'NotAllowedError') {
        setPermissionStatus('denied');
      } else {
        setHasError(true);
      }
      setShowHelp(true);
    } finally {
      setIsChecking(false);
    }
  };

  const getPermissionIcon = () => {
    switch (permissionStatus) {
      case 'granted':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'denied':
        return <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />;
      default:
        return <AudioOutlined />;
    }
  };

  const getPermissionSteps = () => {
    // const browser = getBrowserType(); // 暂时不使用浏览器类型
    
    return [
      {
        title: '点击地址栏权限图标',
        description: `在浏览器地址栏左侧找到锁头或权限图标，点击它`,
      },
      {
        title: '允许麦克风访问',
        description: `在弹出的权限设置中，将麦克风设置为"允许"`,
      },
      {
        title: '刷新页面',
        description: '权限更改后，刷新页面使设置生效',
      }
    ];
  };

  // const getBrowserType = () => {
  //   const userAgent = navigator.userAgent.toLowerCase();
  //   if (userAgent.includes('chrome')) return 'Chrome';
  //   if (userAgent.includes('firefox')) return 'Firefox';
  //   if (userAgent.includes('safari')) return 'Safari';
  //   if (userAgent.includes('edge')) return 'Edge';
  //   return '浏览器';
  // };

  const renderHelpContent = () => (
    <div style={{ maxWidth: 600 }}>
      <Title level={4}>
        <AudioOutlined /> 麦克风权限设置帮助
      </Title>
      
      {!isHttps && (
        <Alert
          type="warning"
          message="安全提示"
          description="当前网站未使用HTTPS协议。某些浏览器可能会限制麦克风功能，建议使用HTTPS访问。"
          style={{ marginBottom: 16 }}
        />
      )}

      <Alert
        type="info"
        message="为了使用语音功能，需要您允许网站访问麦克风"
        style={{ marginBottom: 16 }}
      />

      <Steps direction="vertical" size="small" current={-1}>
        {getPermissionSteps().map((step, index) => (
          <Step
            key={index}
            title={step.title}
            description={step.description}
          />
        ))}
      </Steps>

      <div style={{ marginTop: 16 }}>
        <Text type="secondary">
          如果仍然无法使用麦克风功能，请检查：
        </Text>
        <ul>
          <li>确保麦克风设备已正确连接</li>
          <li>检查系统音频设置中麦克风是否被禁用</li>
          <li>尝试重新加载页面或重启浏览器</li>
          <li>使用现代浏览器（Chrome、Edge、Firefox等）</li>
        </ul>
      </div>
    </div>
  );

  // 如果权限被拒绝，显示帮助按钮
  if (permissionStatus === 'denied') {
    return (
      <>
        {children}
        <Button 
          type="link" 
          size="small" 
          onClick={() => setShowHelp(true)}
          icon={getPermissionIcon()}
          style={{ color: '#ff4d4f' }}
        >
          麦克风权限被拒绝，点击查看帮助
        </Button>
        
        <Modal
          title="麦克风权限帮助"
          visible={showHelp}
          onCancel={() => setShowHelp(false)}
          footer={[
            <Button key="close" onClick={() => setShowHelp(false)}>
              关闭
            </Button>,
            <Button 
              key="retry" 
              type="primary" 
              onClick={requestPermission}
              loading={isChecking}
              disabled={isChecking}
            >
              {isChecking ? '正在请求...' : '重新请求权限'}
            </Button>
          ]}
          width={700}
        >
          {renderHelpContent()}
        </Modal>
      </>
    );
  }

  // 如果权限未知或需要请求，显示请求按钮
  if (permissionStatus === 'prompt' || permissionStatus === 'unknown') {
    return (
      <>
        {children}
        <Button 
          type="primary" 
          size="small" 
          onClick={requestPermission}
          icon={<AudioOutlined />}
          loading={isChecking}
          disabled={isChecking}
        >
          {isChecking ? '正在请求权限...' : '启用麦克风权限'}
        </Button>
      </>
    );
  }

  // 权限正常，直接显示子组件
  return children;
}